/**
 * Created by duzi on 7/6/15.
 */
    $(document).ready(function(){
        var vip = {
            input:{
              name: $('.addcustomer #login-name'),
              phone: $('.addcustomer #login-phone'),
              password: $('.addcustomer #login-pass'),
              address: $('.addcustomer #login-addr')
            },
            regx: {
                name: /^([\u4e00-\u9fa5]+|([a-zA-Z]+\s?)+)$/,
                phone: /^0?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/,
                password: /.*/,
                address: /.*/
            },
            submit: function(){
                if(!this.regx.name.test(this.input.name.val()) || !this.regx.phone.test(this.input.phone.val())){
                    alert('wrong format');
                    return;
                }
                $.ajax({
                    type: "POST",
                    url: "/customers",
                    data: JSON.stringify({name: this.input.name.val(), phone: this.input.phone.val(), passwd: this.input.password.val(), address: this.input.address.val()}),
                    contentType: 'application/json',
                    success: function(response){
                       alert('create success! id is' + response.customerId);
                        $('.addcustomer .form-control').val('');
                    }
                })
            },
            event: function(){
                var self = this;
                this.input.name.on('change', function(){
                    if(!self.regx.name.test(this.value)){
                        alert('wrong name format');
                    }
                });
                this.input.phone.on('change', function(){
                    if(!self.regx.phone.test(this.value)){
                        alert('wrong phone format');
                    }
                });

                $('#addCustomer').on('click', function(){
                    self.submit();
                })
            }
        }

        vip.event();
    })
